import { get } from "../../utils/request";
const app = getApp();
Page({
  data: {
    lessons: [],
    filteredLessons: [],
    url: "",
    value: "",
  },
  async onLoad() {
    let { lesson: lessons } = await get("/lesson");
    this.setData(
      {
        lessons,
        filteredLessons: lessons,
      },
      () => this.playLesson()
    );
  },
  playLesson() {
    let { lessonId } = app.globalData;
    if (lessonId) {
      const lesson = this.data.lessons.find((item) => item._id === lessonId);
      if (lesson) {
        this.setData({ url: lesson.url });
      }
    }
  },
  onShow() {
    this.playLesson();
  },
  watch(event) {
    let { url } = event.currentTarget.dataset;
    this.setData({
      url,
    });
  },
  onSearch(event) {
    let { lessons } = this.data;
    if (event.detail == "") return this.setData({ filteredLessons: lessons });

    this.setData({
      filteredLessons: lessons.filter((item) =>
        item.title.includes(event.detail)
      ),
    });
  },
  addFavorite(event) {
    let { lesson } = event.mark;
    const favorites = wx.getStorageSync("favorites") || {};
    favorites[lesson._id] = lesson;
    wx.setStorageSync("favorites", favorites);
  },
});
